package plenprojects.chatservice;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

import plenprojects.model.ChatMessage;
import plenprojects.security.PermissionType;

public class ChatRoom {
	
	private final static int MAX_MESSAGES_STORED = 20;
	
	private final String name;
	private final Queue<ChatMessage> recentMessages = new LinkedList<ChatMessage>();
	private final Set<String> usersInRoom = new HashSet<String>();
	private final PermissionType[] permissionsOnJoin;
	
	public ChatRoom(String name, PermissionType[] permissionsOnJoin) {
		
		this.name = name;
		this.permissionsOnJoin = permissionsOnJoin;
	}
	
	public String getName() {
		
		return name;
	}
	
	public void addUser(String username) {
		
		usersInRoom.add(username);
	}
	
	public void removeUser(String username) {
		
		usersInRoom.remove(username);
	}
	
	public Set<String> getUsersInRoom() {
		
		return new HashSet<String>(usersInRoom);
	}
	
	public boolean isIn(String username) {
		
		return usersInRoom.contains(username);
	}

	public PermissionType[] getPermissionsOnJoin() {
		
		return permissionsOnJoin;
	}

	public synchronized void submitNewMessage(ChatMessage msg) {
		
		recentMessages.add(msg);
		
		if(recentMessages.size() > MAX_MESSAGES_STORED) {
			
			recentMessages.remove();
		}
	}

	public synchronized Queue<ChatMessage> getRecentMessages() {
		
		return new LinkedList<ChatMessage>(recentMessages);
	}
	
}
